import {
  User,
  Userprofile,
  UserProfileResponse,
  UserReponse,
} from '@/types/data';
import { http } from '@/utils/http';
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

export const getUser = createAsyncThunk('profile/getUser', async () => {
  const res = await http.get<UserReponse>('/user');
  return res.data.data;
});
// 获取个人信息
export const getUserProfile = createAsyncThunk(
  'profile/getUserProfile',
  async () => {
    const res = await http.get<UserProfileResponse>('/user/profile');
    return res.data.data;
  }
);
type UpdateUserProfile = {
  name?: string;
  intro?: string;
  brithday?: string;
  gender?: number;
};

// 修改昵称 调接口
export const UpdateUserProfile = createAsyncThunk(
  'propfile/UpdateUserProfile',
  async (data: UpdateUserProfile) => {
    await http.patch('/user/profile', data);

    //  返回要修改的数据
    return data;
  }
);
// 状态类型
type State = {
  user: User;
  Userprofile: Userprofile;
};
// 状态初始值
const initialState: State = {
  user: {} as User,
  Userprofile: {} as Userprofile,
};
const profile = createSlice({
  name: 'profile',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(getUser.fulfilled, (state, action) => {
      state.user = action.payload;
    });
    builder.addCase(getUserProfile.fulfilled, (state, action) => {
      state.Userprofile = action.payload;
    });
    builder.addCase(UpdateUserProfile.fulfilled, (state, action) => {
      state.Userprofile = {
        ...state.Userprofile,
        ...action.payload,
      };
    });
  },
});

export default profile.reducer;
